package com.zlp.stategy.impl;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.zlp.common.exception.CustomException;
import com.zlp.config.YsSupplierProperties;
import com.zlp.dto.test.*;
import com.zlp.enums.SupplierTypeEnum;
import com.zlp.stategy.CouponSupplierStategy;
import com.zlp.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Classname CouponSupplierYunShengStategyImpl
 * @Description 云生未来实现类
 * @Date 2022/9/21 13:20
 * @Created by ZouLiPing
 */
@Service
@Slf4j(topic = "YsCouponSupplierStategyImpl")
public class YsCouponSupplierStategyImpl implements CouponSupplierStategy {

    @Resource
    private YsSupplierProperties ysSupplierProperties;
    @Resource
    private RestTemplateUtil restTemplateUtil;
    @Resource
    private RedisUtils redisUtils;


    @Override
    public String getToken(String timestamp) {

        String key = SupplierConstant.YS_TOKEN;
        String token = redisUtils.get(key);
        if (StringUtils.isNotBlank(token)) {
            return token;
        }
        String domain = ysSupplierProperties.getDomain();
        String appId = ysSupplierProperties.getAppId();
        String appSecret = ysSupplierProperties.getAppSecret();
        // 签名 = MD5(APP ID + 密钥 + 当前时间（毫秒）/100000)
        String signParam = appId + appSecret + System.currentTimeMillis() / 100000;
        log.info("getToken.MD5Utils.md5 signParam ={}",signParam);
        String sign = MD5Utils.md5(signParam);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", appId);
        paramMap.put("sign", sign);
        try {
            log.info("getToken.req url={},paramMap={}",domain+SupplierConstant.GET_TOKEN, JSON.toJSONString(paramMap));
            ResponseEntity<JSONObject> result = restTemplateUtil.post(domain+SupplierConstant.GET_TOKEN, paramMap, JSONObject.class);
            log.info("getToken.resp url={},result={}",domain+SupplierConstant.GET_TOKEN, JSON.toJSONString(result));
            JSONObject jsonObject = result.getBody();
            restTemplateUtil.checkCodeException(jsonObject, SupplierTypeEnum.YUNSHENG_FUTURE.getCode());
            YsTokenDTO objBean = jsonObject.getBean("data", YsTokenDTO.class);
            restTemplateUtil.checkDataException(objBean);
            token = objBean.getToken();
            redisUtils.setKeyBySECONDS(key,objBean.getToken(),objBean.getExpiresIn()-9*60);
            return token;
        }catch(Exception e){
            log.error("getToken resp error={}",e.getMessage());
            throw new CustomException(500L,e.getMessage(),MethodUtil.getLineInfo());
        }
    }


    @Override
    public List<SupplierSkuDTO> getSupplierSkuList(Object paramMap) {

        String domain = ysSupplierProperties.getDomain();
        try {
            Map<String, String> headers = new HashMap<>();
            String token = this.getToken(String.valueOf(System.currentTimeMillis()));
            headers.put(SupplierConstant.YS_TOKEN_HEADER,token);
            log.info("getSupplierSkuList.req url={},paramMap={},token={}",domain+SupplierConstant.ORDER_COUPON_STAT, JSON.toJSONString(paramMap),token);
            ResponseEntity<JSONObject> result = restTemplateUtil.post(domain+SupplierConstant.ORDER_COUPON_STAT, headers,paramMap, JSONObject.class);
            log.info("getSupplierSkuList.resp url={},result={}",domain+SupplierConstant.GET_TOKEN, JSON.toJSONString(result));
            JSONObject jsonObject = result.getBody();
            restTemplateUtil.checkCodeException(jsonObject, SupplierTypeEnum.YUNSHENG_FUTURE.getCode());
            String response = jsonObject.getStr("data");
            restTemplateUtil.checkDataException(response);
            return JSON.parseArray(response, SupplierSkuDTO.class);
        }catch(Exception e){
            log.error("getSupplierSkuList resp error={}",e.getMessage());
            throw new CustomException(500L,e.getMessage(),MethodUtil.getLineInfo());
        }
    }


    @Override
    public SupplierCardCipherDTO createCoupon(Object paramMap) {

        String domain = ysSupplierProperties.getDomain();
        try {
            Map<String, String> headers = new HashMap<>();
            String token = this.getToken(String.valueOf(System.currentTimeMillis()));
            headers.put(SupplierConstant.YS_TOKEN_HEADER,token);
            log.info("createCoupon.req url={},paramMap={},token={}",domain+SupplierConstant.YS_CREATE_COUPON, JSON.toJSONString(paramMap),token);
            ResponseEntity<JSONObject> result = restTemplateUtil.post(domain+SupplierConstant.YS_CREATE_COUPON, headers,paramMap, JSONObject.class);
            log.info("createCoupon.resp url={},result={}",domain+SupplierConstant.YS_CREATE_COUPON, JSON.toJSONString(result));
            JSONObject jsonObject = result.getBody();
            restTemplateUtil.checkCodeException(jsonObject, SupplierTypeEnum.LI_HAN.getCode());
            String response = jsonObject.getStr("data");
            restTemplateUtil.checkDataException(response);
            return JSON.parseObject(response, SupplierCardCipherDTO.class);
        }catch(Exception e){
            log.error("createCoupon resp error={}",e.getMessage());
            throw new CustomException(500L,e.getMessage(),MethodUtil.getLineInfo());
        }
    }

    @Override
    public List<SupplierBaseDTO> getCouponBaseInfo(Object paraMap) {

        String domain = ysSupplierProperties.getDomain();
        try {
            Map<String, String> headers = new HashMap<>();
            String token = this.getToken(null);
            headers.put(SupplierConstant.YS_TOKEN_HEADER,token);
            log.info("getCouponBaseInfo.req url={},paramMap={},token={}",domain+ SupplierConstant.YS_SKU_BASE_INFO, JSON.toJSONString(paraMap),token);
            ResponseEntity<JSONObject> result = restTemplateUtil.post(domain+SupplierConstant.YS_SKU_BASE_INFO, headers,paraMap, JSONObject.class);
            log.info("getCouponBaseInfo.resp url={},result={}",domain+SupplierConstant.YS_SKU_BASE_INFO, JSON.toJSONString(result));
            JSONObject jsonObject = result.getBody();

            restTemplateUtil.checkCodeException(jsonObject, SupplierTypeEnum.YUNSHENG_FUTURE.getCode());
            String response = jsonObject.getStr("data");
            restTemplateUtil.checkDataException(response);
            return JSON.parseArray(response, SupplierBaseDTO.class);
        }catch(Exception e){
            log.error("createCoupon resp error={}",e.getMessage());
            throw new CustomException(500L,e.getMessage(),MethodUtil.getLineInfo());
        }
    }



}
